package com.m3839.sdk.anti.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.m3839.sdk.anti.core.AntiManager;
import com.m3839.sdk.anti.bean.PopConfigBean;
import com.m3839.sdk.anti.utils.AntiStringUtils;
import com.m3839.sdk.common.base.BaseDialogFragment;
import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.ErrorConstant;
import com.m3839.sdk.common.core.SdkConfiguration;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.util.AppUtils;
import com.m3839.sdk.common.util.FastClickUtils;
import com.m3839.sdk.common.util.LogUtils;
import com.m3839.sdk.common.util.ResourcesUtils;
import com.m3839.sdk.common.util.StringUtils;
import com.m3839.sdk.common.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:HykbAntiDialogFragment
 *
 * @author 陈宝阳
 * @create 2020/8/4 11:04
 */
public class AntiDialogFragment extends BaseDialogFragment {

  /**
   * 用户实名认证的请求码
   */
  private static final int REQUEST_CODE_USER = 1002;

  /**
   * 好游快爆-包名
   */
  private static final String HYKB_PACKAGE_NAME = "com.xmcy.hykb";

  public static final String KEY_CONFIG = "config";
  public static final String KEY_NICK = "nick";
  public static final String KEY_UID = "uid";
  public static final String KEY_LOGIN_TYPE = "platform";
  public static final String KEY_APP_ID = "app_id";

  private TextView switchAccountTv;
  private TextView publicPolicyTv;
  private TextView publicPolicyTipTv;
  private TextView warmTipTv;
  private TextView detailTv;
  private Button negativeBtn;
  private Button positiveBtn;
  private View btnLineView;

  private List<PopConfigBean> configBeans;
  private PopConfigBean configBean;
  private PopConfigBean floatConfigBean;
  private String nick;
  private String uid;
  private String loginType;
  private int beforeStart;

  public static AntiDialogFragment newInstance(List<PopConfigBean> configBeans, String nick,
                                               String uid, String loginType) {
    AntiDialogFragment fragment = new AntiDialogFragment();
    Bundle data = new Bundle();
    data.putParcelableArrayList(KEY_CONFIG, (ArrayList<? extends Parcelable>) configBeans);
    data.putString(KEY_NICK, nick);
    data.putString(KEY_UID, uid);
    data.putString(KEY_LOGIN_TYPE, loginType);
    fragment.setArguments(data);
    return fragment;
  }


  public void update(List<PopConfigBean> configBeans, String nick,
      String uid, String loginType) {
    this.configBeans.clear();
    this.configBeans.addAll(configBeans);
    this.nick = nick;
    this.uid = uid;
    this.loginType = loginType;

    parseConfigBeans();
    setContent();
    initListener();
  }

  public void update(int beforeStart){
    this.beforeStart = beforeStart;
    setContent();
    initListener();
  }

  @Override
  protected void parseArgs() {
    uid = getArguments().getString(KEY_UID);
    nick = getArguments().getString(KEY_NICK);
    loginType = getArguments().getString(KEY_LOGIN_TYPE);
    configBeans = getArguments().getParcelableArrayList(KEY_CONFIG);

    parseConfigBeans();
  }

  private void parseConfigBeans() {
    int size = configBeans != null ? configBeans.size() : 0;
    for (int i = 0; i < size; i++) {
      PopConfigBean bean = configBeans.get(i);
      if (bean == null) {
        continue;
      }

      if (bean.type == 1) {
        configBean = bean;
        beforeStart = configBean.beforeStart;
      } else if (bean.type == 2) {
        floatConfigBean = bean;
      }
    }
  }

  @Override
  protected String getLayoutName() {
    return "anti_dialog_fragment";
  }

  @Override
  protected void initView(View view) {
    Context context = view.getContext();
    switchAccountTv = view.findViewById(getId("tv_switch_account"));
    publicPolicyTv = view.findViewById(getId("tv_public_policy"));
    publicPolicyTipTv = view.findViewById(getId("tv_public_policy_tip"));
    warmTipTv = view.findViewById(getId("tv_warm_tip"));
    detailTv = view.findViewById(getId("tv_detail"));
    negativeBtn = view.findViewById(getId("dlg_btn_negative"));
    positiveBtn = view.findViewById(getId("dlg_btn_positive"));
    btnLineView = view.findViewById(getId("view_btn_line"));
  }

  @Override
  protected void setContent() {
    if (configBean != null) {
      LogUtils.flog(configBean.toString());

      // 防沉迷文案内容
      handleContent();

      // 处理政策提醒内容
      handlePolicyTipContent();

      // 处理温馨提示
      handleWarmTipContent();

      // 处理详情链接
      handleLinkContent();

      // 处理按钮文案
      handleButtonContent();

      // 切换账号功能
      handleLabelContent();
    }
  }

  /**
   * 防沉迷文案内容
   */
  private void handleContent() {
    if (!TextUtils.isEmpty(configBean.content)) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        publicPolicyTv.setText(Html.fromHtml(configBean.content, Html.FROM_HTML_MODE_LEGACY));
      } else {
        publicPolicyTv.setText(Html.fromHtml(configBean.content));
      }
    }
  }

  /**
   * 处理政策提醒内容(包含倒计时文案内容)
   */
  private void handlePolicyTipContent() {
    if(!TextUtils.isEmpty(configBean.beforeStartFormat)){
      publicPolicyTipTv.setVisibility(View.VISIBLE);
      String tip = AntiStringUtils.getPublicTip(beforeStart,
              configBean.beforeStartFormat, configBean.beforeStartText);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        publicPolicyTipTv.setText(Html.fromHtml(tip, Html.FROM_HTML_MODE_LEGACY));
      } else {
        publicPolicyTipTv.setText(Html.fromHtml(tip));
      }
    }else if (!TextUtils.isEmpty(configBean.beforeStartText)) {
      publicPolicyTipTv.setVisibility(View.VISIBLE);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        publicPolicyTipTv.setText(Html.fromHtml(configBean.beforeStartText, Html.FROM_HTML_MODE_LEGACY));
      } else {
        publicPolicyTipTv.setText(Html.fromHtml(configBean.beforeStartText));
      }
    }else {
      publicPolicyTipTv.setVisibility(View.GONE);
    }
  }

  /**
   * 处理温馨提示文案
   */
  private void handleWarmTipContent() {
    if (!TextUtils.isEmpty(configBean.tips)) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        warmTipTv.setText(
                Html.fromHtml(configBean.tips, Html.FROM_HTML_MODE_LEGACY));
      } else {
        warmTipTv.setText(Html.fromHtml(configBean.tips));
      }
      warmTipTv.setVisibility(View.VISIBLE);
    } else {
      warmTipTv.setVisibility(View.GONE);
    }
  }

  /**
   * 处理详情链接
   */
  private void handleLinkContent() {
    if (configBean.linkBean != null && !TextUtils.isEmpty(configBean.linkBean.name) &&
            !TextUtils.isEmpty(configBean.linkBean.url)){
      detailTv.setText(configBean.linkBean.name);
      detailTv.setVisibility(View.VISIBLE);
    } else{
      detailTv.setVisibility(View.GONE);
    }
  }

  /**
   * 处理按钮文案
   */
  private void handleButtonContent() {
    if (configBean.buttonBeanList != null && configBean.buttonBeanList.size() > 0) {
      negativeBtn.setText(configBean.buttonBeanList.get(0).name);
    }

    if (configBean.buttonBeanList != null && configBean.buttonBeanList.size() > 1) {
      positiveBtn.setText(configBean.buttonBeanList.get(1).name);
      positiveBtn.setVisibility(View.VISIBLE);
      btnLineView.setVisibility(View.VISIBLE);
      negativeBtn.setBackgroundResource(
              ResourcesUtils.getDrawableId(getActivity(), "hykb_bg_default_dialog_left_btn"));
    } else {
      positiveBtn.setVisibility(View.GONE);
      btnLineView.setVisibility(View.GONE);
      negativeBtn.setBackgroundResource(
              ResourcesUtils.getDrawableId(getActivity(), "hykb_bg_default_dialog_single_btn"));
    }
  }

  /**
   * 处理弹窗顶部标签的文案
   */
  private void handleLabelContent() {
    if(configBean.labelBean != null && configBean.labelBean.show
            && SdkConfiguration.getSdkEnv() == Constant.ENV_ANTI) {
      switchAccountTv.setVisibility(View.VISIBLE);
      switchAccountTv.setText(configBean.labelBean.name);
    }else {
      switchAccountTv.setVisibility(View.GONE);
    }
  }

  @Override
  protected void initListener() {
    detailTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (configBean != null && configBean.linkBean != null && StringUtils.isValidHttpUrl(
            configBean.linkBean.url)) {
          //用手机浏览器打开点击的链接
          AppUtils.openUrl(getActivity(), configBean.linkBean.url);
        }
      }
    });

    negativeBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (configBean.buttonBeanList != null && configBean.buttonBeanList.size() > 0) {
          handleAction(configBean.buttonBeanList.get(0).func);
        }
      }
    });

    positiveBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (configBean.buttonBeanList != null && configBean.buttonBeanList.size() > 1) {
          handleAction(configBean.buttonBeanList.get(1).func);
        }
      }
    });

    switchAccountTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if(configBean.labelBean != null && configBean.labelBean.show
                && SdkConfiguration.getSdkEnv() == Constant.ENV_ANTI) {
          SubjectBus.get().postValue(Constant.HYKB_EVENT_ANTI_SWITCH_ACCOUNT, null);
        }
      }
    });
  }

  /**
   * 防沉迷弹窗事件
   * @param action 按钮行为
   */
  private void handleAction(String action) {
    if (Constant.ACTION_EXIT_GAME.equals(action)) {
      // 退出游戏
      dismiss();
      SubjectBus.get().observe(Constant.HYKB_EVENT_ANTI_RESET, null);
      AntiManager.getInstance().resetToken();
      AppUtils.killAllProcess(getActivity());
      return;
    }

    if (Constant.ACTION_WSSFXX.equals(action)) {
      if (FastClickUtils.isFastDoubleClick()) {
        return;
      }
      // 完善身份信息
      openIdCardActivity();
      return;
    }

    if (Constant.ACTION_EXIT_POPUP.equals(action)) {
      // 关闭弹窗后，再显示悬浮气泡
      if (floatConfigBean != null) {
        AntiManager.getInstance()
                .showFloatBubble(floatConfigBean.content, floatConfigBean.linkBean);
      }
      ApiError apiError = new ApiError(ErrorConstant.HYKB_CODE_DIALOG_ANTI_CLOSE,
              ErrorConstant.ERR_MSG_SDK_DIALOG_ANTI_CLOSE);
      SubjectBus.get().postValue(Constant.HYKB_EVENT_ANTI_CALLBACK, apiError);
      dismiss();
    }
  }

  /**
   * 跳转到快爆完成实名认证
   */
  private void openIdCardActivity() {
    if (!AppUtils.checkVersionCode(getActivity(),HYKB_PACKAGE_NAME, 237)) {
      AntiManager.getInstance().toRealNameWeb(getActivity());
    } else {
      Intent intent = new Intent("android.intent.action.VIEW");
      intent.putExtra(KEY_UID, uid);
      intent.putExtra(KEY_NICK, nick);
      intent.putExtra(KEY_LOGIN_TYPE, loginType);
      intent.putExtra(KEY_APP_ID, SdkConfiguration.getGameId());
      //固定字段
      intent.putExtra("key", "loginsdk");
      ComponentName componentName = new ComponentName(HYKB_PACKAGE_NAME,
              "com.xmcy.hykb.app.ui.idcard.IdCardActivity");
      intent.setComponent(componentName);
      startActivityForResult(intent, REQUEST_CODE_USER);
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_USER && data != null) {
      boolean status = data.getBooleanExtra("status", false);
      String msg = data.getStringExtra("msg");
      LogUtils.flog("m3839", "status = " + status + ", msg = " + msg);
      if (!status) {
        if (!TextUtils.isEmpty(msg)) {
          ToastUtil.showToast(getActivity(), msg);
        }
        return;
      }

      // 重新拉取数据
      AntiManager.getInstance().resetToken();
      AntiManager.getInstance().onBeat();
      dismiss();
    }
  }

}
